package train

import (
	"aquaman/app/biz/m"
	"aquaman/app/biz/train/model"
	infraDB "aquaman/app/infra/db"
	"aquaman/app/infra/ecode"
	infraLog "aquaman/app/infra/log"
	"context"
	"reflect"
	"strings"
)

type Service struct {
	db 				*infraDB.DB
	logger          infraLog.CtxLogger
	repo			*model.Repository
}

func NewService(
	db 		*infraDB.DB,
	logger 	infraLog.CtxLogger,
	repo 	*model.Repository,
) *Service {
	return &Service{
		db:     db,
		logger: logger,
		repo:	repo,
	}
}

type Station struct {
	DBKey 		string
	Prority		int64
}

var StationMap = map[string]*Station{
	"金山卫":&Station{
		DBKey:   "jsw",
		Prority: 0,
	},
	"金山园区":&Station{
		DBKey:   "jsyq",
		Prority: 1,
	},
	"亭林":&Station{
		DBKey:   "tl",
		Prority: 2,
	},
	"叶榭":&Station{
		DBKey:   "yx",
		Prority: 3,
	},
	"车墩":&Station{
		DBKey:   "cd",
		Prority: 4,
	},
	"新桥":&Station{
		DBKey:   "xq",
		Prority: 5,
	},
	"春申":&Station{
		DBKey:   "cs",
		Prority: 6,
	},
	"上海南":&Station{
		DBKey:   "shn",
		Prority: 7,
	},
}

var priceTable = [][]int64 {
	[]int64{0,3,3,5,6,7,8,10},
	[]int64{3,0,3,3,4,5,6,8},
	[]int64{3,3,0,3,3,4,5,6},
	[]int64{5,3,3,0,3,3,4,5},
	[]int64{6,4,3,3,0,3,3,4},
	[]int64{7,5,4,3,3,0,3,3},
	[]int64{8,6,5,4,3,3,0,3},
	[]int64{10,8,6,5,4,3,3,0},
}


func (s *Service) GetTrains(scheme uint64,departOn string,begin string,end string,ctx context.Context)(list []*m.Train) {

	if scheme != 1 && scheme != 2 {
		panic(ecode.Error(ecode.ParamInvaild,"非法参数"))
	}
	if len(departOn) == 0 || len(begin) == 0 || len(end) == 0 {
		panic(ecode.Error(ecode.ParamInvaild,"非法参数"))
	}
	beginStation,isOK := StationMap[begin]
	if !isOK {
		panic(ecode.Error(ecode.ParamInvaild,"起点不存在该火车站"))
	}
	endStation,isOK := StationMap[end]
	if !isOK {
		panic(ecode.Error(ecode.ParamInvaild,"终点不存在该火车站"))
	}
	var (
		direction int64
		stationCount int64
	)
	if endStation.Prority - beginStation.Prority < 0 {
		direction = 2
		stationCount = beginStation.Prority - endStation.Prority
	}else {
		direction = 1
		stationCount = endStation.Prority - beginStation.Prority
	}

	originList := s.repo.GetTrainsV2(scheme,departOn,beginStation.DBKey,endStation.DBKey,direction)
	for _,value := range originList {
		v := reflect.ValueOf(value)
		departOn := v.FieldByName(strings.ToUpper(beginStation.DBKey)).String()
		arriveAt := v.FieldByName(strings.ToUpper(endStation.DBKey)).String()
		price := priceTable[beginStation.Prority][endStation.Prority]
		var sc int64
		if value.Type == "直达" {
			sc = 1
		}else if value.Type == "大站停" {
			if stationCount < 4 {
				sc = 1
			}else if stationCount < 7 {
				sc = 2
			}else {
				sc = 3
			}
		}else {
			sc = stationCount
		}
		list = append(list, &m.Train{
			Name:         value.Name,
			DepartOn:     departOn,
			ArriveAt:     arriveAt,
			BeginStation: begin,
			EndStation:   end,
			StationCount: sc,
			TrainType:    value.Type,
			Price:        price,
		})
	}



	return
}

